package com.zhongxi.guoyuan.view.user;

import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.user.UserResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.RegularTool;
import com.zhongxi.guoyuan.view.MainHomeActivity;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private TextView tvRegister;
    private TextView tvForgot;
    private TextView tvLogin;
    private EditText etPhone;
    private EditText etCode;
    private EditText etPassword;
    private int position;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_login);
        initTitle();
        tvTitle.setText("会员登录");
        ivBack = (ImageView) findViewById(R.id.ivBack);
        tvRegister = (TextView) findViewById(R.id.tvRegister);
        tvForgot = (TextView) findViewById(R.id.tvForgot);
        tvLogin = (TextView) findViewById(R.id.tvLogin);
        etPhone = (EditText) findViewById(R.id.etPhone);
        etPassword = (EditText) findViewById(R.id.etPassword);
        position = getIntent().getIntExtra("position", 0);
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        tvRegister.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        tvForgot.setOnClickListener(this);
        tvLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvRegister:
                startAct(RegisterActivity.class);
                break;
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvForgot:
                startAct(ForgotPasswordActivity.class);
                break;
            case R.id.tvLogin:
                login();
                break;
        }
    }

    /**
     * 登录
     */
    private void login() {
        String phone = etPhone.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        if(TextUtils.isEmpty(phone)){
            showShortToast("手机号不能为空");
        }else if(!RegularTool.isPhoneNumberValid(phone)){
            showShortToast("请输入正确的手机号");
        }else if(TextUtils.isEmpty(password)){
            showShortToast("请输入密码");
        }else{
            Map<String, String> map = new HashMap<String, String>();
            map.put("mobilenum", MyApplication.getInstance().descsc(phone));
            map.put("pwd", MyApplication.getInstance().descsc(password));
            getServer(Url.LOGIN, map, "", false, null, "post");
        }
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        try {
            Gson gson = new Gson();
            UserResult result = gson.fromJson(response, UserResult.class);
            MyApplication.getInstance().setSpValue(result.getSafeobj());
            SharedPreferences sharedPrefrences = getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
            sharedPrefrences.edit().putString("phone", result.getData().getMphone()).commit();
            sharedPrefrences.edit().putString("userid", result.getData().getId()).commit();
            sharedPrefrences.edit().putString("username", result.getData().getUsername()).commit();
            sharedPrefrences.edit().putString("shopname", result.getData().getShopname()).commit();
            sharedPrefrences.edit().putString("rmb", result.getExtend().getRmb()).commit();
            sharedPrefrences.edit().putString("silver", result.getExtend().getSilver()).commit();
            sharedPrefrences.edit().putString("inner", result.getExtend().getInnercurrency()).commit();
            sharedPrefrences.edit().putString("num", result.getExtend().getId()+"").commit();
            sharedPrefrences.edit().putString("avatar", result.getData().getAvatar()+"").commit();
            sharedPrefrences.edit().putString("time", result.getData().getCtime()+"").commit();
            if(null!=result.getData().getIsshareholders()&&!"".equals(result.getData().getIsshareholders()))
                sharedPrefrences.edit().putBoolean("shareHolder", "1".equals(result.getData().getIsshareholders())).commit();
            if(null!=result.getData().getIsprivilege()&&!"".equals(result.getData().getIsprivilege()))
                sharedPrefrences.edit().putBoolean("privilege", "1".equals(result.getData().getIsprivilege())).commit();
            if(position == 0){   //默认情况
                startAct(MainHomeActivity.class);
            }else{
                Intent intent = new Intent();  //红包搜一搜的回调
                setResult(RESULT_OK, intent);
                finish();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj()))
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        try {
            JSONObject obj = new JSONObject(response);
            int errorCode = obj.getInt("code");
            if(errorCode == 1000){
//                showShortToast("参数错误");
            }else if(errorCode == 1003){
                showShortToast("用户已登录");
            }else if(errorCode == 7003){
                showShortToast("密码错误");
            }else if(errorCode == 7004){
                showShortToast("用户未注册，请先注册");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void processOldUser(String response) {
        super.processOldUser(response);
        Gson gson = new Gson();
        try{
            showShortToast("您已注册，未设置密码，请先设置密码后登陆");
            Intent intent = new Intent(context, ForgotPasswordActivity.class);
            intent.putExtra("type", 1);
            startActivity(intent);
            BaseResponse baseBean = gson.fromJson(response, BaseResponse.class);
            if(null!=baseBean.getSafeobj()&&!"".equals(baseBean.getSafeobj()))
             MyApplication.getInstance().setSpValue(baseBean.getSafeobj());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
